<template>
    <div class="role-management-container">
        <pageTitle :title="'角色管理'" />
        <!-- 顶部搜索和按钮区域 -->
        <div class="top-action-bar">
            <el-row :gutter="20" align="middle">
                <el-col :span="12">
                    <el-input placeholder="请输入角色名稱" v-model="searchQuery" class="search-input-with-button" clearable
                        @clear="handleSearch" @keyup.enter="handleSearch">
                        <template #append>
                            <el-button type="primary" @click="handleSearch">
                                <el-icon>
                                    <Search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="12" class="action-buttons">
                    <el-button type="primary" @click="addRole">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <span>新增角色</span>
                    </el-button>
                </el-col>
            </el-row>
        </div>

        <!-- 主体内容区域 -->
        <div class="main-content-wrapper">
            <el-row :gutter="20">
                <!-- 左侧角色列表树 -->
                <el-col :span="5">
                    <div class="role-list-card">
                        <div class="tree-header">
                            <span class="tree-title">角色列表</span>
                            <el-button type="text" @click="refreshRoleList">
                                <el-icon>
                                    <Refresh />
                                </el-icon>
                                <span>刷新</span>
                            </el-button>
                        </div>
                        <el-tree :data="roleList" :props="treeProps" node-key="id" highlight-current
                            :expand-on-click-node="false" @node-click="handleRoleClick">
                            <template #default="{ node, data }">
                                <span class="custom-tree-node">
                                    <span>{{ node.label }}</span>
                                    <span class="node-actions">
                                        <el-button type="text" size="small" @click.stop="editRole(data)">
                                            <el-icon>
                                                <Edit />
                                            </el-icon>
                                        </el-button>
                                        <el-button type="text" size="small" @click.stop="deleteRole(data)">
                                            <el-icon>
                                                <Delete />
                                            </el-icon>
                                        </el-button>
                                    </span>
                                </span>
                            </template>
                        </el-tree>
                    </div>
                </el-col>

                <!-- 右侧員工表格 -->
                <el-col :span="19">
                    <div class="employee-table-card">
                        <el-table :data="employeeList" style="width: 100%" v-loading="loading" class="no-border-table"
                            @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="55" />
                            <el-table-column prop="name" label="員工名稱" width="120" align="center" />
                            <el-table-column prop="employeeId" label="員工编号" width="120" align="center" />
                            <el-table-column prop="phone" label="手機號碼" width="150" align="center" />
                            <el-table-column prop="department" label="部門" align="center" />
                            <el-table-column prop="position" label="職位" width="150" align="center" />
                            <el-table-column label="管理範圍" align="center">
                                <template #default="{ row }">
                                    <div class="scope-cell">
                                        <span>{{ row.scope || '未設置' }}</span>
                                        <el-button type="text" size="small" @click="setScope(row)">
                                            <el-icon>
                                                <Setting />
                                            </el-icon>
                                            設置
                                        </el-button>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="120" align="center" fixed="right">
                                <template #default="{ row }">
                                    <el-button type="danger" size="small" @click="removeEmployee(row)">
                                        移除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="pagination-wrapper">
                            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                                :page-sizes="[10, 20, 50, 100]" :small="true" :background="true"
                                layout="total, sizes, prev, pager, next, jumper" :total="total"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>

        <!-- 新增/编辑角色对话框 -->
        <el-dialog v-model="roleDialogVisible" :title="isEditRole ? '编辑角色' : '新增角色'" width="500px">
            <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="80px">
                <el-form-item label="角色名稱" prop="name">
                    <el-input v-model="roleForm.name" placeholder="请输入角色名稱" />
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="roleForm.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="roleDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitRoleForm">確定</el-button>
            </template>
        </el-dialog>

        <!-- 設置管理範圍对话框 -->
        <el-dialog v-model="scopeDialogVisible" title="設置管理範圍" width="600px">
            <el-form :model="scopeForm" label-width="100px">
                <el-form-item label="管理範圍">
                    <el-tree :data="scopeOptions" show-checkbox node-key="id" :default-expanded-keys="['1']"
                        :props="scopeProps" v-model:checked-keys="scopeForm.checkedKeys" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="scopeDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveScope">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Search, Plus, Refresh, Edit, Delete, Setting } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import pageTitle from "@/components/pageTitle/pageTitle.vue";

// 响应式数据
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const selectedRows = ref([]);

// 角色相关数据
const roleList = ref([
    { id: 1, name: '行政', description: '行政管理人員角色' },
    { id: 2, name: '人事', description: '人力资源管理人員角色' },
    { id: 3, name: '策划', description: '活动策划人員角色' },
    { id: 4, name: '财务', description: '财务管理人員角色' },
    { id: 5, name: '技术', description: '技术人員角色' }
]);

const treeProps = {
    label: 'name',
    children: 'children'
};

// 員工表格数据
const employeeList = ref([
    {
        id: 1,
        name: '张三',
        employeeId: '10001',
        phone: '13800138001',
        department: '行政部',
        position: '行政专員',
        scope: '行政部、人事部'
    },
    {
        id: 2,
        name: '李四',
        employeeId: '10002',
        phone: '13800138002',
        department: '人事部',
        position: '人事专員',
        scope: '全公司'
    },
    {
        id: 3,
        name: '王五',
        employeeId: '10003',
        phone: '13800138003',
        department: '策划部',
        position: '策划经理',
        scope: '策划部、市场部'
    },
    {
        id: 4,
        name: '赵六',
        employeeId: '10004',
        phone: '13800138004',
        department: '财务部',
        position: '会计',
        scope: '财务部'
    },
    {
        id: 5,
        name: '钱七',
        employeeId: '10005',
        phone: '13800138005',
        department: '技术部',
        position: '前端工程师',
        scope: '技术部'
    }
]);

// 角色表单相关
const roleDialogVisible = ref(false);
const isEditRole = ref(false);
const roleForm = ref({
    id: null,
    name: '',
    description: ''
});
const roleRules = {
    name: [{ required: true, message: '请输入角色名稱', trigger: 'blur' }]
};
const roleFormRef = ref(null);

// 管理範圍相关
const scopeDialogVisible = ref(false);
const scopeForm = ref({
    employeeId: null,
    checkedKeys: []
});
const scopeOptions = ref([
    {
        id: '1',
        name: '全公司',
        children: [
            { id: '1-1', name: '行政部' },
            { id: '1-2', name: '人事部' },
            { id: '1-3', name: '财务部' },
            { id: '1-4', name: '技术部' },
            { id: '1-5', name: '市场部' },
            { id: '1-6', name: '策划部' }
        ]
    }
]);
const scopeProps = {
    label: 'name',
    children: 'children'
};

// 生命周期钩子
onMounted(() => {
    fetchEmployeeData();
});

// 方法
const fetchEmployeeData = () => {
    loading.value = true;
    // 模拟API请求
    setTimeout(() => {
        total.value = employeeList.value.length;
        loading.value = false;
    }, 500);
};

const handleSearch = () => {
    currentPage.value = 1;
    fetchEmployeeData();
};

const refreshRoleList = () => {
    ElMessage.success('角色列表已刷新');
};

const handleRoleClick = (data) => {
    console.log('点击角色:', data);
    fetchEmployeeData();
};

const addRole = () => {
    isEditRole.value = false;
    roleForm.value = {
        id: null,
        name: '',
        description: ''
    };
    roleDialogVisible.value = true;
};

const editRole = (data) => {
    isEditRole.value = true;
    roleForm.value = { ...data };
    roleDialogVisible.value = true;
};

const deleteRole = (data) => {
    ElMessageBox.confirm(`確定要删除角色「${data.name}」吗?`, '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        roleList.value = roleList.value.filter(item => item.id !== data.id);
        ElMessage.success('删除成功');
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

const submitRoleForm = () => {
    roleFormRef.value.validate((valid) => {
        if (valid) {
            if (isEditRole.value) {
                // 更新角色
                const index = roleList.value.findIndex(item => item.id === roleForm.value.id);
                if (index !== -1) {
                    roleList.value[index] = { ...roleForm.value };
                }
                ElMessage.success('角色更新成功');
            } else {
                // 新增角色
                const newId = Math.max(...roleList.value.map(item => item.id)) + 1;
                roleList.value.push({
                    ...roleForm.value,
                    id: newId
                });
                ElMessage.success('角色新增成功');
            }
            roleDialogVisible.value = false;
        }
    });
};

const handleSelectionChange = (selection) => {
    selectedRows.value = selection;
};

const setScope = (row) => {
    scopeForm.value = {
        employeeId: row.id,
        checkedKeys: row.scope ? row.scope.split('、').map(item => {
            const match = scopeOptions.value[0].children.find(opt => opt.name === item);
            return match ? match.id : null;
        }).filter(Boolean) : []
    };
    scopeDialogVisible.value = true;
};

const saveScope = () => {
    const checkedNodes = scopeOptions.value[0].children.filter(item =>
        scopeForm.value.checkedKeys.includes(item.id)
    );
    const scopeText = checkedNodes.length === scopeOptions.value[0].children.length
        ? '全公司'
        : checkedNodes.map(item => item.name).join('、');

    const employee = employeeList.value.find(item => item.id === scopeForm.value.employeeId);
    if (employee) {
        employee.scope = scopeText;
    }

    ElMessage.success('管理範圍設置成功');
    scopeDialogVisible.value = false;
};

const removeEmployee = (row) => {
    ElMessageBox.confirm(`確定要将「${row.name}」从當前角色中移除吗?`, '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        employeeList.value = employeeList.value.filter(item => item.id !== row.id);
        total.value = employeeList.value.length;
        ElMessage.success('移除成功');
    }).catch(() => {
        ElMessage.info('已取消移除');
    });
};

const handleSizeChange = (val) => {
    pageSize.value = val;
    fetchEmployeeData();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchEmployeeData();
};
</script>

<style scoped lang="less">
.role-management-container {
    padding: 20px;
    background-color: #fff;

    .top-action-bar {
        margin-bottom: 20px;
        padding: 16px 24px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        margin-top: 20px;

        .search-input-with-button {
            max-width: 500px;

            .el-input-group__append {
                background-color: var(--el-color-primary);
                color: white;
                border: none;

                &:hover {
                    opacity: 0.9;
                }
            }
        }

        .action-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 12px;

            .el-button {
                display: inline-flex;
                align-items: center;
                gap: 6px;
            }
        }
    }

    .main-content-wrapper {
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        padding: 16px;
        min-height: calc(100vh - 320px);
    }

    .role-list-card {
        border: 1px solid #ebeef5;
        border-radius: 8px;
        padding: 16px;
        height: 100%;
        background-color: #fff;

        .tree-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0 16px;

            .tree-title {
                font-size: 16px;
                font-weight: 600;
                color: #303133;
            }

            .el-button {
                display: inline-flex;
                align-items: center;
                gap: 4px;
            }
        }

        .custom-tree-node {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 14px;
            padding-right: 8px;

            .node-actions {
                visibility: hidden;
            }

            &:hover .node-actions {
                visibility: visible;
            }
        }

        .el-tree {
            :deep(.el-tree-node__content) {
                height: 36px;
            }
        }
    }

    .employee-table-card {
        padding: 16px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        background-color: #fff;

        .scope-cell {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .no-border-table {

            :deep(.el-table__header),
            :deep(.el-table__body),
            :deep(.el-table__row),
            :deep(.el-table__cell) {
                border: none !important;
            }

            :deep(.el-table__header th) {
                background-color: #f4f8ff;
                font-weight: 600;
                padding: 20px;
            }

            :deep(.el-table__row):hover td {
                background-color: #f5f7fa !important;
            }
        }

        .pagination-wrapper {
            margin-top: 24px;
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>